<template>
  <!--目录导航-->
  <my-cata
    :titles="tag_title"
    :preview="preview"
    :handleAnchorClick="handleAnchorClick"
  ></my-cata>
  <!--文档内容-->
  <el-row>
    <el-col :span="19">
      <!--文档部分-->
      <v-md-preview
        ref="preview"
        :text="mymd"
        preview-class="vuepress-markdown-body"
        :height="editHeight+'px'"
      >
      </v-md-preview>
      <!--可运行代码-->
      <my-code
        :codeList="current.docInfo.code"
      ></my-code>
      <!--加载组件-->
      <my-comp
        :doc="current.docInfo"
      ></my-comp>
    </el-col>
    <el-col :span="5"></el-col>
  </el-row>
   
</template>

<script>
  import { ref, computed,reactive, watch, onMounted } from 'vue'
  import { ElRow, ElCol } from 'element-plus'
  // import mdController from '../service/md.js'
  import myCode from '../runCode/code-show-list.vue'
  import myComp from '../runCode/load-comp.vue'
  import config from '../config/index.js'

  // 目录连接
  // import myList from './md-catalogue.vue'

  // 状态
  import { store } from '@naturefw/nf-state'

</script>

<script setup>
  
  const myCata = config.myCata

  const props = defineProps({
    // current: Object
  })
  const current = store.current // props.current

  // 替换文档里的标签
  const mymd = computed(() => current.docInfo.md.replace(/{_baseUrl_}/g, config.baseUrl))

  // 可见的高度
  const editHeight = document.documentElement.clientHeight - 200
  // const { loadDocById } = mdController()

  const preview = ref(null)
  
  const titles = reactive([])
  const tag_title = reactive([])

  let anchors = null

  // 设置标题导航
  const setAnchors = () => {
    titles.length = 0
    tag_title.length = 0

    anchors = preview.value.$el.querySelectorAll('h1,h2,h3,h4,h5,h6')
    titles.push(...Array.from(anchors).filter((title) => !!title.innerText.trim()))

    if (!titles.length) {
      tag_title.length = 0
    }

    const hTags = Array.from(
      new Set(titles.map((title) => title.tagName))
    ).sort()

    tag_title.push(
      ...titles.map((el) => ({
        title: el.innerText,
        lineIndex: el.getAttribute('data-v-md-line'),
        indent: hTags.indexOf(el.tagName)
      }))
    )
  }

  // 渲染后，获取目录导航
  onMounted(() => {
    setAnchors()
  })

  // 更换菜单后，更新目录导航
  watch(() => current.menuInfo.menuId, (id) => {
    setTimeout(() => {
      titles.length = 0
      setAnchors()
    }, 300)
  })

  // 点击导航，定位目录位置
  const handleAnchorClick = (anchor) => {
    const { lineIndex } = anchor

    const heading = preview.value.$el.querySelector(`[data-v-md-line="${lineIndex}"]`)

    if (heading) {
      preview.value.scrollToTarget({
        target: heading,
        scrollContainer: window,
        top: 60
      })
    }
  }

</script>